package thread.synchroCode;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class Ali_1123PaymentClass {
    /**
     * 过滤不可用支付方式类型
     *
     * @param paymentTypeList  原始支付方式类型列表
     * @return 可用支付方式类型列表
     */
    public List<String> allowPayType = new ArrayList<>();
    public List<String> allPayType = new ArrayList<>();
    public Integer index = 0;

    public Ali_1123PaymentClass() {
        allowPayType.add("余额");
        allowPayType.add("红包");
        allowPayType.add("优惠券");
        allowPayType.add("代金券");
    }

    public synchronized void addAllowPayType(String payType){
        this.allowPayType.add(payType);
    }

    public synchronized String getPayType(Integer index){
        if (index >= allPayType.size()){
            return "";
        }
        return this.allPayType.get(index++);
    }

    public void getAllowPayType() throws InterruptedException {
        int size = allPayType.size();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            new Thread(()-> {
                String currPayType = this.getPayType(index);
                // 请求接口查询支付方式是否可用
                ConsultResult res = PaymentRemoteSerivce.isEnabled(currPayType);
                if (res.isEnable){
                    this.addAllowPayType(currPayType);
                } else {
                    System.out.println("当前支付方式" + currPayType + "不可用，错误码为：" + res.errorCode);
                }
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println(this.allowPayType);
    }

    public static class ConsultResult {
        public ConsultResult(boolean isEnable, String errorCode) {
            this.isEnable = isEnable;
            this.errorCode = errorCode;
        }

        /** 咨询结果是否可用 */
        private boolean isEnable;

        /** 错误码 */
        private String errorCode;
    }

    public static class PaymentRemoteSerivce{
        public static Random random = new Random();
        public static ConsultResult isEnabled(String currPayType){
            int i = random.nextInt(10);
            if (i % 2 == 0){
                return new ConsultResult(true,"");
            }
            return new ConsultResult(false,String.valueOf(random.nextInt(10)));
        }
    }
}